#include<iostream>
#include<string>
#include<memory>
#include<jsoncpp/json/json.h>


//实现数据的序列化和反序列化
bool serialize(const Json::Value &val , std::string &body)
{

    std::stringstream ss;
    Json::StreamWriterBuilder swb;//先实列化工厂类对象 ，用其生产streamwriter对象

    std::unique_ptr<Json::StreamWriter> sw (swb.newStreamWriter());
    int ret = sw->write(val , &ss);
    if(ret !=0)
    {
        std::cout<< "json serialize error\n";
        return false;
    }
    body =ss.str();
    return true;
    //智能指针自动释放
    // //一定要释放sw
    // delete sw;

}


bool Deserialize(const std::string &body ,  Json::Value &val)
{
    Json::CharReaderBuilder CRB;//先实列化工厂类对象
    std::unique_ptr<Json::CharReader> cr (CRB.newCharReader());

    std::string errs;
    int ret = cr->parse(body.c_str() ,body.c_str()+body.size(), &val ,&errs );
    if(ret == false)
    {
         std::cout<< "json Deserialize error "<<errs << std::endl;
        return false;
    }
    return true;

}

int main()
{

    const char *name ="小明";
    int age =18;
    const char* sex ="男";
    float score[3]= {88.5 ,99,68};

    Json::Value student;
    student["姓名"]=name;
    student["年龄"]=age;
    student["性别"]=sex;
    student["成绩"].append(score[0]);
    student["成绩"].append(score[1]);
    student["成绩"].append(score[2]);


    Json::Value fav;
    fav["书籍"]="西游记";
    fav["运动"]="打篮球";
    student["爱好"]=fav;

    std::string body;
    serialize(student ,body);
    std::cout<<body;

    std::string str =R"({"姓名":"李四" ,"年龄":20 , "成绩" : [20 ,99 ,99.6]})";
    Json::Value stu2;
    int ret =Deserialize(str ,stu2);
    if(ret == false)
    {
        return -1;
    }
    std::cout<<"姓名"<<stu2["姓名"].asString()<<std::endl;
    std::cout<<"年龄"<<stu2["年龄"].asInt()<<std::endl;
    int sz =stu2["成绩"].size();
    for(int i =0 ;i<sz ;i++ )
    {
        std::cout<<"成绩"<<stu2["成绩"][i].asFloat()<<std::endl;
    }

    return 0;
}